<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card class="box-card">
            <el-row :gutter="20">
            <el-col :span="7">
                 <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="queryAllUsers">
                    <el-button slot="append" icon="el-icon-search"  @click="queryUsers()"></el-button>
                </el-input>
            </el-col>
            <el-col :span="4">
                <el-button type="primary" @click="addUserDialog">添加用户</el-button>
            </el-col>
            </el-row>

              <el-table
                :data="userList"
                style="width: 100%"
                border
                stripe>
                 <el-table-column type="index" width="50">
                 </el-table-column>
                <el-table-column prop="username" label="姓名">
                </el-table-column>
                <el-table-column prop="email" label="邮箱">
                </el-table-column>
                 <el-table-column prop="moblie" label="电话">
                </el-table-column>
                 <el-table-column  prop="roleName" label="角色">
                </el-table-column>
                <el-table-column label="状态">
                  <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" @change="changeStatus(scope.row)">
                    </el-switch>
                  </template>
                </el-table-column>
                <el-table-column  label="操作" width="180">
                  <template slot-scope="scope">
                   <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditUserDialog(scope.row.id)"></el-button>
                   <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(scope.row.id)"></el-button>

                    <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                      <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>

              </el-table>

               <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[2, 4, 10, 20]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
              </el-pagination>
        </el-card>

        <el-dialog
          title="添加用户"
          :visible.sync="addUserDialogVisible"
          width="50%"
          @close="addUserDialogClose">

          <el-form ref="addUserRef" :model="addUserForm" label-width="70px"
          :rules="addUserRules">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addUserForm.username"></el-input>
            </el-form-item>

             <el-form-item label="密码" prop="password">
              <el-input v-model="addUserForm.password"></el-input>
            </el-form-item>

             <el-form-item label="邮箱" prop="email">
              <el-input v-model="addUserForm.email"></el-input>
            </el-form-item>

             <el-form-item label="手机" prop="phone">
              <el-input v-model="addUserForm.phone"></el-input>
            </el-form-item>

          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="addUserDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>

        <el-dialog
          title="编辑用户"
          :visible.sync="editUserDialogVisible"
          width="50%"
          @close="closeEditUserDialog">

          <el-form :model="editUserForm" :rules="addUserRules" ref="editUserRef" label-width="70px">
            <el-form-item label="用户名">
              <el-input v-model="editUserForm.username" disabled></el-input>
            </el-form-item>

             <el-form-item label="邮箱" prop="email">
              <el-input v-model="editUserForm.email"></el-input>
            </el-form-item>

            <!-- prop中的名称要和v-model中的名称一致，不然会找不到数据，导致验证失败 -->
             <el-form-item label="用户名" prop="phone">
              <el-input v-model="editUserForm.phone"></el-input>
            </el-form-item>

          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="editUserDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUser">确 定</el-button>
          </span>
        </el-dialog>

    </div>

</template>

<script>
export default {
  data () {
    var checkEmail = (rule, value, callback) => {
      console.log(11)
      const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (!reg.test(value)) {
        return callback(new Error('邮箱不合法'))
      }
      callback()
    }
    var checkPhone = (rule, value, callback) => {
      const reg = /^1([38]\d|5[0-35-9]|7[3678])\d{8}$/
      if (!reg.test(value)) {
        return callback(new Error('手机号不合法'))
      }
      callback()
    }

    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      addUserDialogVisible: false,
      editUserDialogVisible: false,
      addUserForm: {},
      editUserForm: {},
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 9 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮件', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      }

    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('/users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
      console.log('getuserList')
    },
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    changeStatus (row) {
      console.log(row)
      // 未作具体请求实现该功能
      this.$message.success('更改状态成功')
    },
    queryUsers () {
      console.log(this.queryInfo.query)
      this.getUserList()
    },
    queryAllUsers () {
      this.getUserList()
    },

    addUserDialog () {
      this.addUserDialogVisible = true
    },
    addUserDialogClose () {
      this.$refs.addUserRef.resetFields()
    },
    addUser () {
      this.$refs.addUserRef.validate(vaild => {
        if (!vaild) return
        // TODO 添加用户接口
        // this.$http.post()
        this.$message.success('添加成功')
        this.getUserList()
        this.addUserDialogVisible = false
      })
    },
    async showEditUserDialog (id) {
      const { data: res } = await this.$http.get(`/user/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户数据失败')
      }
      this.editUserForm = res.data
      this.editUserDialogVisible = true
    },
    closeEditUserDialog () {
      this.$refs.editUserRef.resetFields()
    },
    editUser () {
      this.$refs.editUserRef.validate(vaild => {
        if (!vaild) {
          return this.$message.error('编辑内容不合法')
        }
        // TODO 更新数据库
        // this.$http.post()
        this.$message.success('编辑成功')
        this.editUserDialogVisible = false
      })
    },
    delUser (id) {
      console.log(id)
      // 写法1
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO 请求删除
        // this.$http.delete()
        // 刷新列表
        this.getUserList()
        this.$message.success('删除成功!')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }

  }

}
</script>

<style lang="less" scoped>

</style>
